package com.jh.concurrent.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title ReentrantReadWriteLockDemo.java
 * @package com.jh.concurrent.lock
 * @description 重入读写锁Demo
 * @date 2019-05-16 22:52
 */
public class ReentrantReadWriteLockDemo {

    private static Map<String, Object> map = new HashMap<>();

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static void getCacheData(String key) {
        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        readLock.lock();
        try {
            System.out.println("开始读数据 -------------------");
            System.out.println("缓存的值：" + map.get(key));
        } finally {
            readLock.unlock();
        }
    }

    public static void setCacheData(String key, Object data) {
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
        writeLock.lock();
        try {
            System.out.println("开始设置缓存值 --------------------");
            map.put(key, data);
            System.out.println("设置缓存值成功！");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(() -> setCacheData("1", 1)).start();
        new Thread(() -> getCacheData("1")).start();

    }

}
